package com.ai.controller.acquisition;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ai.common.constant.WseSectionConstants;
import com.ai.common.constant.WseSectionConstantsHy;
import com.ai.common.controller.BaseController;
import com.ai.common.exception.BusinessException;
import com.ai.common.model.Pagination;
import com.ai.common.model.Result;
import com.ai.common.util.ZipUtils;
import com.ai.model.edu.cms.info.InfoDetail;
import com.ai.model.edu.cms.info.dto.InfoDetailDTO;
import com.ai.model.edu.cms.info.vo.InfoDetailVO;
import com.ai.service.cms.info.InfoDetailService;
import com.ai.service.cms.sensitiveword.SensitiveWordService;

/**
 * 
 * Class Name : AcquisitionController<br>
 * 
 * Description : 采集编辑文章controller类<br>
 * 
 */
@Controller
public class AcquisitionController extends BaseController {

	@Resource
	private InfoDetailService infoDetailService;
	@Value("${mainDomain}")
	private String mainDomain;
	@Resource
	private SensitiveWordService sensitiveWordService;

	/**
	 * Description ：新增资讯
	 * 
	 * @author Administrator 2015年6月16日 下午3:58:29
	 * @return
	 *
	 */
	@RequestMapping("/article/initArticle")
	public String initArticle() {
		return "/acquisition/initArticle";
	}

	@RequestMapping(value = "/article/findThemeMapByChannelId", method = RequestMethod.POST)
	@ResponseBody
	public Result findThemeMapByChannelId(Long locChannelId) {
		Result result = new Result(true);
		try {
			String themeStr = WseSectionConstants.menuMap
					.get(locChannelId.toString());
			Map themeMap = new HashMap();
						
			String[] themeArray = themeStr.split(",");			
			for (int i = 0; i < themeArray.length; i++) {
				themeMap.put(themeArray[i],
						WseSectionConstants.sectionMap.get(themeArray[i]));
			}
			
			result.addAttribute("themeMap", themeMap);
		} catch (Exception e) {
			result.setSuccess(false);
			log.error("获取二级菜单失败");
		}
		return result;
	}

	@RequestMapping(value = "/article/addArticle", method = RequestMethod.POST)
	public String addArticle(Model model, InfoDetail infoDetail,
			HttpServletRequest request,
			@RequestParam(value = "file", required = false) MultipartFile[] file,
			@RequestParam(value = "xjhyfile", required = false) MultipartFile xjhyfile)
					throws Exception {
		model.addAttribute("infoDetailId", infoDetail.getId());
		
		//update by chenchang 2016/3/9
		String files = "";
		if(infoDetail.getLocThemeId()==98)
		{
			files = uploadDoc(xjhyfile);
		}else {
			files = uploadDoc(file, infoDetail.getTitle());
		}
		//end update
				
//		if (StringUtils.isBlank(files)) {
//			throw new Exception("上传文件失败");
//		}
		if(request.getParameter("coverPicUrlXJHY").length()!=0)
		{
			infoDetail.setCoverPicUrl(request.getParameter("coverPicUrlXJHY").toString());
		}
		infoDetail.setAttach(files);
		infoDetail.setCreateBy(getBackendOperator(request).getId());
		infoDetailService.insertInfoDetail(infoDetail);
		return "/acquisition/initSuccess";
	}

	/**
	 * 上传
	 * 
	 * @date 2015年11月14日 下午10:03:31
	 * @param articleFile
	 * @return
	 * @throws Exception
	 *             String
	 */
	private String uploadDoc(MultipartFile[] articleFile, String name)
			throws Exception {
		/*if (articleFile == null) {
			return null;
		}*/
		int flag=0;
		if (articleFile.length<=0) 
		{
			return null;
		}
		else
		{
			for(int i=0;i<articleFile.length;i++)
			{
				if(articleFile[i].getSize()>0)
				{
					flag=1;
					break;
				}
			}
		}
		
		if(flag==0)
		{
			return null;
		}
		
		validFiles(articleFile);// 校验文件
		Random rdm = new Random(System.currentTimeMillis());
		String baseFolder = this.getClass().getClassLoader()
				.getResource("../../upload/doc").getPath();
		String uploadFolder = baseFolder + UUID.randomUUID()
				+ System.currentTimeMillis();
		File folder = new File(uploadFolder);
		if (folder.exists()) {
			ZipUtils.delFolder(uploadFolder);
		}
		folder.mkdir();
		for (MultipartFile multipartFile : articleFile) {
			if(multipartFile == null || multipartFile.isEmpty()) {
				continue;
			}
			String fileName = System.currentTimeMillis()
					+ Math.abs(rdm.nextInt()) + "."
					+ FilenameUtils
							.getExtension(multipartFile.getOriginalFilename())
							.toLowerCase();
			FileUtils.copyInputStreamToFile(multipartFile.getInputStream(),
					new File(folder, fileName));
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String zipName = name + "_" + System.currentTimeMillis() + ".zip";
		ZipUtils.compress(uploadFolder, baseFolder + zipName, true);
		return mainDomain + "/upload/doc/" +  zipName;
	}

	/**
	 * 
	 * 校验文件
	 * 
	 * @date 2015年11月15日 下午1:26:54
	 * @param articleFile
	 * @throws Exception
	 *             void
	 */
	private void validFiles(MultipartFile[] articleFile) throws Exception {
		if (articleFile == null) {
			return;
		}
		long size = 0;
		for (MultipartFile multipartFile : articleFile) {
			if(multipartFile == null || multipartFile.isEmpty()) {
				continue;
			}
			String fileName = multipartFile.getOriginalFilename();
			if (!Pattern.compile("^.*?\\.(doc|docx|ppt|pptx|zip|tar|pdf|xls)$")
					.matcher(fileName.toLowerCase()).matches()) {
				BusinessException.throwMessage(
						"文件格式错误，目前仅支持doc|docx|ppt|pptx|zip|tar|pdf|xls");
			}
			if (multipartFile.getSize() > 1024 * 1024 * 5) {
				BusinessException.throwMessage("单个文件最大不能超过5M");
			}
			size += multipartFile.getSize();
		}
		// 校验文件总大小
		if (size > 1024 * 1024 * 12) {
			BusinessException.throwMessage("文件总大小不能超过15M");
		}

	}

	public static void main(String[] args) {
		Random rdm = new Random(System.currentTimeMillis());
		for (int i = 0; i < 10; i++) {
			System.out.println(Math.abs(rdm.nextInt()));
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
	}

	@ResponseBody
	@RequestMapping(value = "/article/focusNews/{id}", method = RequestMethod.POST)
	public Result focusNews(@PathVariable("id") Long id) {
		InfoDetailVO info = infoDetailService.findInfoDetailById(id);
		if (info == null) {
			return new Result(false, "文章不存在");
		}
		if (info.getInfoStatus() != 0) {
			return new Result(false, "已发布的新闻不能再设置为焦点新闻");
		}
		if (info.getLocChannelId() != 1) {
			return new Result(false, "该文章类型不能设置为焦点新闻");
		}
		if (StringUtils.isBlank(info.getCoverPicUrl())) {
			return new Result(false, "焦点新闻至少需要一张图片");
		}
		if ("1".equals(info.getFileUrl())) {
			return new Result(false, "该文章已经是焦点新闻了");
		}
		info.setFileUrl("1");
		infoDetailService.updateInfoDetail(info);
		return new Result(true);
	}

	@RequestMapping(value = "/article/addAndPublishArticle", method = RequestMethod.POST)
	public String addAndPublishArticle(Model model, InfoDetail infoDetail,
			HttpServletRequest request) {
		infoDetail.setCreateBy(getBackendOperator(request).getId());
		Long newArticleId = infoDetailService.insertInfoDetail(infoDetail);
		return "redirect:" + mainDomain + "/info/publish.action?infoIds="
				+ newArticleId;
	}

	@RequestMapping(value = "/article/batchPublishArticle", method = RequestMethod.POST)
	@ResponseBody
	public Result publishArticle(String infoIds, HttpServletRequest request) {
		Result result = new Result(true, "");
		if (StringUtils.isNotBlank(infoIds)) {
			String[] idArr = infoIds.split(",");
			try {
				for (String id : idArr) {
					InfoDetail info = new InfoDetail();
					info.setId(Long.valueOf(id));
					info.setUpdateBy(getBackendOperator(request).getId());
					info.setInfoStatus(Byte.valueOf("3"));
					infoDetailService.updateInfoDetail(info);
				}
			} catch (Exception e) {
				log.error("publish Article failed!");
				result.setSuccess(false);
			}
		}

		return result;
	}

	@RequestMapping("/upload/toPicUpload")
	public String toPicUpload1(HttpServletRequest request) {
		return "/upload/picUpload";
	}

	@RequestMapping(value = "/article/queryArticleList", method = RequestMethod.GET)
	public String queryArticle(Model model) {
		// List<SectionInfoVO> sectionList =
		// sectionInfoService.findAllEffectSectionList();
		// model.addAttribute("sectionList", sectionList);
		return "/acquisition/queryArticleList";
	}

	@RequestMapping(value = "/article/doQueryArticleList", method = RequestMethod.POST)
	@ResponseBody
	public Pagination<InfoDetailVO> doQueryArticle(InfoDetailDTO infoDetailDTO,
			HttpServletRequest request) {
		Map<String, String> menuMap = WseSectionConstants.menuMap;
		List<String> list = new ArrayList<String>();
		if (menuMap.size()>0) {
			Iterator i = menuMap.entrySet().iterator();
			while (i.hasNext()) { 
			    Map.Entry entry = (Map.Entry) i.next(); 
			    Object key = entry.getKey(); 
			    list.add(key.toString()); 
			}
			infoDetailDTO.setThemeList(list);
		}
		return infoDetailService.findInfoDetailPageByDto(infoDetailDTO, true);
	}

	@RequestMapping("/article/deleteArticle/{id}")
	@ResponseBody
	public Result deleteArticle(@PathVariable Long id,
			HttpServletRequest request) {
		return infoDetailService.deleteArticle(id,
				getBackendOperator(request).getId());
	}

	@RequestMapping("/article/publishArticle/{id}")
	@ResponseBody
	public Result publishArticle(@PathVariable Long id,
			HttpServletRequest request) {
		InfoDetail info = new InfoDetail();
		info.setId(Long.valueOf(id));
		info.setUpdateBy(getBackendOperator(request).getId());
		info.setInfoStatus(Byte.valueOf("3"));
		Long r = infoDetailService.updateInfoDetail(info);
		Result result = new Result(true, "");
		if (r == 0) {
			result.setSuccess(false);
		}
		return result;
	}

	@RequestMapping("/article/editArticle/{id}")
	public ModelAndView editArticle(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/acquisition/initArticle");
		InfoDetailVO vo = infoDetailService.selectInfoDetailById(id);
		mv.addObject(vo);
		return mv;
	}

	@RequestMapping(value = "/article/previewArticle", method = RequestMethod.POST)
	public ModelAndView previewAriticle(InfoDetailVO infoDetailVO) {
		ModelAndView mv = new ModelAndView("info/infoDetailPage");
		mv.addObject(infoDetailVO);
		return mv;
	}

	@RequestMapping(value = "/article/checkSensitiveWord", method = RequestMethod.POST)
	@ResponseBody
	public Result checkSensitiveWord(String txt) {
		Result result = new Result(true);
		Set<String> checkResult = sensitiveWordService.getSensitiveWord(txt, 2);
		if (CollectionUtils.isNotEmpty(checkResult)) {
			result.addAttribute("data", checkResult);
		} else {
			result.setSuccess(false);
		}
		return result;
	}

	/**
	 * 资讯详情页
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/article/infoDetailPage/{id}")
	public ModelAndView infoPublishDetailPage(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		mv.setViewName("info/infoDetailPage");
		InfoDetailVO vo = infoDetailService.selectInfoDetailById(id);
		mv.addObject(vo);
		return mv;
	}
	
	
	/**
	 * 上传星级会员图片
	 * 
	 * @date 2015年11月14日 下午10:03:31
	 * @param articleFile
	 * @return
	 * @throws Exception
	 *             String
	 */
	private String uploadDoc(MultipartFile articleFile)
			throws Exception {
		
		if(articleFile==null||articleFile.getSize()<=0)
		{
			return null;
		}
		
		// 校验文件
		if (!Pattern.compile("^.*?\\.(jpg|png|gif|bmp|jpeg)$")
				.matcher(articleFile.getOriginalFilename().toLowerCase()).matches()) {
			BusinessException.throwMessage(
					"文件格式错误，目前仅支持jpg|png|gif|bmp|jpeg");
		}
		if (articleFile.getSize() > 1024 * 1024 * 5) {
			BusinessException.throwMessage("单个文件最大不能超过5M");
		}
		
		String baseFolder = this.getClass().getClassLoader()
				.getResource("../../upload/images").getPath();
		File folder = new File(baseFolder);
//		if (folder.exists()) {
//			ZipUtils.delFolder(baseFolder);
//		}
//		folder.mkdir();
		
		String newFileName = UUID.randomUUID() + articleFile.getOriginalFilename().substring(articleFile.getOriginalFilename().lastIndexOf("."));
		
		FileUtils.copyInputStreamToFile(articleFile.getInputStream(),
				new File(folder,newFileName));
		return mainDomain + "/upload/images/" +  newFileName;
	}
}
